'use client';

import { useState, useEffect } from 'react';
import Image from 'next/image';
import MediaSelector from '@/components/admin/MediaSelector';

interface News {
  id: string;
  title: string;
  summary: string;
  content: string;
  image?: string;
  images?: string[];
  category: 'news' | 'achievement' | 'event' | 'announcement';
  author: string;
  publishDate: string;
  isPublished: boolean;
  isPinned: boolean;
  viewCount: number;
  createdAt: string;
  updatedAt: string;
}

export default function NewsManagePage() {
  const [news, setNews] = useState<News[]>([]);
  const [loading, setLoading] = useState(true);
  const [showAddForm, setShowAddForm] = useState(false);
  const [editingNews, setEditingNews] = useState<News | null>(null);
  const [formData, setFormData] = useState({
    title: '',
    summary: '',
    content: '',
    category: 'news' as 'news' | 'achievement' | 'event' | 'announcement',
    author: 'admin',
    publishDate: new Date().toISOString().split('T')[0],
    isPublished: true,
    isPinned: false,
    image: '',
    images: [] as string[]
  });
  const [showMediaSelector, setShowMediaSelector] = useState(false);
  const [mediaSelectorMode, setMediaSelectorMode] = useState<'single' | 'multiple'>('single');

  useEffect(() => {
    fetchNews();
  }, []);

  const fetchNews = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/admin/news');
      if (response.ok) {
        const data = await response.json();
        if (data.success) {
          setNews(data.data);
        }
      }
    } catch (error) {
      console.error('Error fetching news:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      if (editingNews) {
        // 更新新闻
        const response = await fetch(`/api/news/${editingNews.id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(formData)
        });
        
        if (response.ok) {
          await fetchNews();
          setEditingNews(null);
        }
      } else {
        // 添加新闻
        const response = await fetch('/api/admin/news', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(formData)
        });
        
        if (response.ok) {
          await fetchNews();
        }
      }
      
      setShowAddForm(false);
      resetForm();
    } catch (error) {
      console.error('Error saving news:', error);
    }
  };

  const resetForm = () => {
    setFormData({
      title: '',
      summary: '',
      content: '',
      category: 'news',
      author: 'admin',
      publishDate: new Date().toISOString().split('T')[0],
      isPublished: true,
      isPinned: false,
      image: '',
      images: []
    });
  };

  const handleEdit = (newsItem: News) => {
    setEditingNews(newsItem);
    setFormData({
      title: newsItem.title,
      summary: newsItem.summary,
      content: newsItem.content,
      category: newsItem.category,
      author: newsItem.author,
      publishDate: newsItem.publishDate.split('T')[0],
      isPublished: newsItem.isPublished,
      isPinned: newsItem.isPinned,
      image: newsItem.image || '',
      images: newsItem.images || []
    });
    setShowAddForm(true);
  };

  const handleDelete = async (id: string) => {
    if (confirm('确定要删除这条新闻吗？')) {
      try {
        const response = await fetch(`/api/news/${id}`, {
          method: 'DELETE'
        });
        
        if (response.ok) {
          await fetchNews();
        }
      } catch (error) {
        console.error('Error deleting news:', error);
      }
    }
  };

  const handleTogglePublished = async (id: string) => {
    const newsItem = news.find(n => n.id === id);
    if (newsItem) {
      try {
        const response = await fetch(`/api/news/${id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            ...newsItem,
            isPublished: !newsItem.isPublished
          })
        });
        
        if (response.ok) {
          await fetchNews();
        }
      } catch (error) {
        console.error('Error updating news:', error);
      }
    }
  };

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>, type: 'single' | 'multiple' = 'single') => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

    const formData = new FormData();
    Array.from(files).forEach(file => {
      formData.append('files', file);
    });

    try {
      const response = await fetch('/api/upload', {
        method: 'POST',
        body: formData
      });
      
      if (response.ok) {
        const data = await response.json();
        if (data.success && data.data.files.length > 0) {
          if (type === 'single') {
            setFormData(prev => ({ ...prev, image: data.data.files[0] }));
          } else {
            setFormData(prev => ({ 
              ...prev, 
              images: [...prev.images, ...data.data.files] 
            }));
          }
        }
      }
    } catch (error) {
      console.error('文件上传失败:', error);
      alert('文件上传失败，请重试');
    }
  };

  const removeImage = (index: number) => {
    setFormData(prev => ({
      ...prev,
      images: prev.images.filter((_, i) => i !== index)
    }));
  };

  const handleMediaSelect = (files: string[]) => {
    if (mediaSelectorMode === 'single') {
      setFormData(prev => ({ ...prev, image: files[0] || '' }));
    } else {
      setFormData(prev => ({ 
        ...prev, 
        images: [...prev.images, ...files] 
      }));
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
        <span className="ml-3 text-gray-600">加载中...</span>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">新闻管理</h1>
          <p className="text-gray-600 mt-1">管理网站展示的新闻动态</p>
        </div>
        <button
          onClick={() => setShowAddForm(true)}
          className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
        >
          ➕ 发布新闻
        </button>
      </div>

      {/* News List */}
      <div className="bg-white rounded-lg shadow overflow-hidden">
        <div className="px-6 py-4 border-b border-gray-200">
          <h2 className="text-lg font-semibold">新闻列表</h2>
        </div>
        <div className="divide-y divide-gray-200">
          {news.length === 0 ? (
            <div className="px-6 py-8 text-center text-gray-500">
              暂无新闻，点击上方按钮发布新闻
            </div>
          ) : (
            news.map((newsItem) => (
              <div key={newsItem.id} className="px-6 py-4 hover:bg-gray-50">
                <div className="flex items-center justify-between min-w-0">
                  <div className="flex items-center space-x-4 flex-1 min-w-0 overflow-hidden">
                    <div className="flex-shrink-0">
                      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                        newsItem.category === 'achievement' ? 'bg-yellow-100 text-yellow-800' :
                        newsItem.category === 'event' ? 'bg-green-100 text-green-800' :
                        newsItem.category === 'announcement' ? 'bg-purple-100 text-purple-800' :
                        'bg-blue-100 text-blue-800'
                      }`}>
                        {newsItem.category === 'achievement' ? '🏆 成就' :
                         newsItem.category === 'event' ? '📅 活动' :
                         newsItem.category === 'announcement' ? '📢 公告' :
                         '📰 新闻'}
                      </span>
                    </div>
                    
                    <div className="flex-1 min-w-0 overflow-hidden">
                      <h3 className="text-sm font-medium text-gray-900 flex items-start">
                        <span className="break-words pr-2 flex-1 min-w-0">
                          {newsItem.title}
                        </span>
                        {newsItem.isPinned && (
                          <span className="ml-2 text-xs bg-red-100 text-red-800 px-2 py-0.5 rounded whitespace-nowrap flex-shrink-0">置顶</span>
                        )}
                      </h3>
                      <div className="text-sm text-gray-500 mt-1 break-words" style={{
                        display: '-webkit-box',
                        WebkitLineClamp: 2,
                        WebkitBoxOrient: 'vertical',
                        overflow: 'hidden'
                      }}>
                        {newsItem.summary || newsItem.content.substring(0, 100) + '...'}
                      </div>
                      <div className="text-xs text-gray-400 mt-1 min-w-0 overflow-hidden">
                        <div className="sm:flex sm:space-x-4 space-y-1 sm:space-y-0 flex-wrap">
                          <span className="break-words min-w-0">作者: {newsItem.author}</span>
                          <span className="whitespace-nowrap">发布: {new Date(newsItem.publishDate).toLocaleDateString('zh-CN')}</span>
                          <span className="whitespace-nowrap">查看: {newsItem.viewCount}</span>
                        </div>
                      </div>
                    </div>

                    <div className="flex items-center space-x-2 flex-shrink-0">
                      <button
                        onClick={() => handleTogglePublished(newsItem.id)}
                        className={`px-2 py-1 text-xs rounded whitespace-nowrap ${
                          newsItem.isPublished 
                            ? 'bg-green-100 text-green-800' 
                            : 'bg-gray-100 text-gray-800'
                        }`}
                      >
                        {newsItem.isPublished ? '👁️ 已发布' : '🙈 草稿'}
                      </button>
                      
                      <button
                        onClick={() => handleEdit(newsItem)}
                        className="text-blue-600 hover:text-blue-800 p-1 flex-shrink-0"
                      >
                        ✏️
                      </button>
                      
                      <button
                        onClick={() => handleDelete(newsItem.id)}
                        className="text-red-600 hover:text-red-800 p-1 flex-shrink-0"
                      >
                        🗑️
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            ))
          )}
        </div>
      </div>

      {/* Add/Edit Form Modal */}
      {showAddForm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-4xl max-h-[90vh] overflow-y-auto">
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-xl font-bold">
                {editingNews ? '编辑新闻' : '发布新闻'}
              </h2>
              <button
                onClick={() => {
                  setShowAddForm(false);
                  setEditingNews(null);
                  resetForm();
                }}
                className="text-gray-500 hover:text-gray-700"
              >
                ✕
              </button>
            </div>

            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    新闻分类 *
                  </label>
                  <select
                    required
                    value={formData.category}
                    onChange={(e) => setFormData({ ...formData, category: e.target.value as any })}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  >
                    <option value="news">📰 新闻</option>
                    <option value="achievement">🏆 成就</option>
                    <option value="event">📅 活动</option>
                    <option value="announcement">📢 公告</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    发布日期 *
                  </label>
                  <input
                    type="date"
                    required
                    value={formData.publishDate}
                    onChange={(e) => setFormData({ ...formData, publishDate: e.target.value })}
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    作者
                  </label>
                  <input
                    type="text"
                    value={formData.author}
                    onChange={(e) => setFormData({ ...formData, author: e.target.value })}
                    placeholder="输入作者姓名"
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  />
                </div>

                <div className="flex items-center space-x-4 pt-6">
                  <label className="flex items-center">
                    <input
                      type="checkbox"
                      checked={formData.isPublished}
                      onChange={(e) => setFormData({ ...formData, isPublished: e.target.checked })}
                      className="mr-2"
                    />
                    <span className="text-sm font-medium text-gray-700">立即发布</span>
                  </label>
                  
                  <label className="flex items-center">
                    <input
                      type="checkbox"
                      checked={formData.isPinned}
                      onChange={(e) => setFormData({ ...formData, isPinned: e.target.checked })}
                      className="mr-2"
                    />
                    <span className="text-sm font-medium text-gray-700">置顶显示</span>
                  </label>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  新闻标题 *
                </label>
                <input
                  type="text"
                  required
                  value={formData.title}
                  onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                  placeholder="输入新闻标题"
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  新闻摘要
                </label>
                <textarea
                  value={formData.summary}
                  onChange={(e) => setFormData({ ...formData, summary: e.target.value })}
                  rows={2}
                  placeholder="输入新闻摘要（可选）"
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>

              <div className="space-y-4">
                {/* 封面图片 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    封面图片
                  </label>
                  <div className="space-y-3">
                    <div className="flex gap-2">
                      <input
                        type="file"
                        onChange={(e) => handleFileUpload(e, 'single')}
                        accept="image/*"
                        className="flex-1 border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      />
                      <button
                        type="button"
                        onClick={() => {
                          setMediaSelectorMode('single');
                          setShowMediaSelector(true);
                        }}
                        className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors text-sm"
                      >
                        📁 媒体库
                      </button>
                    </div>
                    {formData.image && (
                      <div className="mt-2 flex items-center space-x-2">
                        <div className="relative w-20 h-20">
                          <Image
                            src={formData.image}
                            alt="封面图片"
                            fill
                            className="object-cover rounded-lg"
                            onError={(e) => {
                              e.currentTarget.src = '';
                            }}
                          />
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center justify-between">
                            <span className="text-sm text-gray-600">当前图片:</span>
                            <button
                              type="button"
                              onClick={() => setFormData(prev => ({ ...prev, image: '' }))}
                              className="text-red-600 hover:text-red-800 text-sm"
                            >
                              删除
                            </button>
                          </div>
                          <div className="text-sm text-blue-600 mt-1 break-all">
                            {formData.image}
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                </div>

                {/* 多图片上传 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    多图片轮播 (可选)
                  </label>
                  <div>
                    <div className="flex gap-2">
                      <input
                        type="file"
                        onChange={(e) => handleFileUpload(e, 'multiple')}
                        accept="image/*"
                        multiple
                        className="flex-1 border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      />
                      <button
                        type="button"
                        onClick={() => {
                          setMediaSelectorMode('multiple');
                          setShowMediaSelector(true);
                        }}
                        className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors text-sm"
                      >
                        📁 媒体库
                      </button>
                    </div>
                    <p className="text-xs text-gray-500 mt-1">
                      支持选择多张图片，在前台将以轮播形式展示
                    </p>
                    {formData.images.length > 0 && (
                      <div className="mt-3">
                        <div className="text-sm font-medium text-gray-700 mb-2">
                          已上传图片 ({formData.images.length}张):
                        </div>
                        <div className="grid grid-cols-3 md:grid-cols-4 gap-2">
                          {formData.images.map((image, index) => (
                            <div key={index} className="relative group">
                              <div className="relative w-20 h-20">
                                <Image
                                  src={image}
                                  alt={`图片${index + 1}`}
                                  fill
                                  className="object-cover rounded-lg"
                                  onError={(e) => {
                                    e.currentTarget.src = '';
                                  }}
                                />
                              </div>
                              <button
                                type="button"
                                onClick={() => removeImage(index)}
                                className="absolute -top-2 -right-2 w-6 h-6 bg-red-600 text-white rounded-full text-xs hover:bg-red-700 opacity-0 group-hover:opacity-100 transition-opacity"
                              >
                                ×
                              </button>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  新闻内容 *
                </label>
                <textarea
                  required
                  value={formData.content}
                  onChange={(e) => setFormData({ ...formData, content: e.target.value })}
                  rows={12}
                  placeholder="输入新闻内容，支持HTML格式"
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
                <p className="text-xs text-gray-500 mt-1">
                  支持HTML标签，如 &lt;p&gt;、&lt;h2&gt;、&lt;img&gt;、&lt;a&gt; 等
                </p>
              </div>

              <div className="flex justify-end space-x-3 pt-4">
                <button
                  type="button"
                  onClick={() => {
                    setShowAddForm(false);
                    setEditingNews(null);
                    resetForm();
                  }}
                  className="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50"
                >
                  取消
                </button>
                <button
                  type="submit"
                  className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
                >
                  {editingNews ? '更新新闻' : '发布新闻'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Media Selector */}
      <MediaSelector
        isOpen={showMediaSelector}
        onClose={() => setShowMediaSelector(false)}
        onSelect={handleMediaSelect}
        multiple={mediaSelectorMode === 'multiple'}
        title={mediaSelectorMode === 'single' ? '选择封面图片' : '选择轮播图片'}
      />
    </div>
  );
}